package com.ch.light.web.service.impl;

import com.ch.light.web.model.User;
import com.ch.light.web.service.LoginService;
import com.ch.light.web.service.UserService;
import com.ch.type.StatusType;
import com.ch.utils.CommonUtils;
import com.ch.utils.DateUtils;
import com.google.common.base.Strings;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.google.common.base.Preconditions.checkArgument;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserService userService;

    @Override
    public User doLogin(String account, String clientIp) {
        checkArgument(!Strings.isNullOrEmpty(account), "帐号不能为空");
        String accountToUse = account.toUpperCase();
        User user = userService.findByUsername(accountToUse);
        if (user == null) {
            //帐号不存在
            throw new UnknownAccountException();
        }
        if (CommonUtils.isEquals(user.getLocked(), StatusType.ENABLED)) {
            //帐号被锁定
            throw new LockedAccountException();
        }
        user.setLoginAt(DateUtils.currentTime());
        user.setLoginIp(clientIp);
        user.setErrorCount(0);
        userService.update(user);
        return user;
    }
}
